#!perl

use strict;
use warnings;
use Cwd qw(abs_path);
use File::Basename;
use File::Spec;
use Test;

my $testdir;
my $scstadmin_pm_dir;
my $scstadmin_dir;
my $scstadmin;
my $redirect_file;
my $redirect;

BEGIN {
    $redirect_file = "/tmp/scstadmin-test-06-output.txt";
    unlink($redirect_file);
    $testdir = dirname(abs_path($0));
    $scstadmin_pm_dir = dirname($testdir);
    $scstadmin_dir = dirname($scstadmin_pm_dir);
    $scstadmin = File::Spec->catfile($scstadmin_dir, "scstadmin");
    unless(grep /blib/, @INC) {
	unshift(@INC, File::Spec->catdir($scstadmin_pm_dir, "lib"));
    }
    plan tests => 6;
}

use Data::Dumper;
use SCST::SCST;
use File::Temp qw/tempfile/;

sub setup {
    my $SCST = shift;

    my ($drivers, $errorString) = $SCST->drivers();
    my %drivers = map { $_ => 1 } @{$drivers};
    ok(exists($drivers{'ib_srpt'}));
}

sub testRestoreConfig {
    my $to_be_restored = shift;
    my $expected = shift;
    my $tmpfilename1 = File::Spec->catfile(File::Spec->tmpdir(),
					   "scstadmin-test-06-$$-1");
    my $tmpfilename2 = File::Spec->catfile(File::Spec->tmpdir(),
					   "scstadmin-test-06-$$-2");
    my $scstadmin_output = File::Spec->catfile(File::Spec->tmpdir(),
					   "scstadmin-test-06-$$-adm-out");
    my $diff         = File::Spec->catfile(File::Spec->tmpdir(),
					   "scstadmin-test-06-$$-diff");

    ok(system("$scstadmin -clear_config -force -noprompt -no_lip $redirect"),
       0);
    ok(system("$scstadmin -cont_on_err -no_lip -config $to_be_restored" .
	      " > " . $scstadmin_output . " 2>&1"), 256);
    ok(system("$scstadmin -write_config $tmpfilename1 >/dev/null"), 0);
    ok(system("awk 'BEGIN {t = 0 } /^# Automatically generated by SCST Configurator v/ " .
	      '{ $0 = "# Automatically generated by SCST Configurator v..." } ' .
	      '/^TARGET_DRIVER.*{$/ { if ($0 != "TARGET_DRIVER scst_local {") t = 1 } ' .
	      '/^}$/ { if (t == 1) t = 2 }' .
	      '/^$/ { if (t == 2) { t = 3 } }' .
	      '/^./ { if (t == 3) { t = 0 } }' .
	      "{ if (t == 0) print }' <$tmpfilename1 >$tmpfilename2"), 0);
    my $compare_result = system("diff -u $tmpfilename2 $expected >$diff");
    ok($compare_result, 0);
    if ($compare_result == 0) {
	unlink($diff);
	unlink($tmpfilename2);
	unlink($tmpfilename1);
    }
}

my $_DEBUG_ = 0;
if ($_DEBUG_) {
    $redirect = ">>$redirect_file";
    open(my $logfile, '>>', $redirect_file);
    select $logfile;
} else {
    $redirect = ">/dev/null";
}

unlink("/var/lib/scst/vdev_mode_pages/disk01");

my $SCST = eval { new SCST::SCST($_DEBUG_) };
die("Creation of SCST object failed") if (!defined($SCST));

setup($SCST);

testRestoreConfig(File::Spec->catfile($testdir, "06-to-be-restored.conf"),
		  File::Spec->catfile($testdir, "06-after-restore.conf"));

